import { useState, useEffect } from 'react'
import { storage } from '@/services/storage'

export const useDeckManagement = () => {
  const [decks, setDecks] = useState([])
  const [selectedDeck, setSelectedDeck] = useState(null)
  const [deckCards, setDeckCards] = useState([])
  const [toast, setToast] = useState({ show: false, message: '' })

  // 添加初始化加载
  useEffect(() => {
    refreshDecks()
  }, [])

  const refreshDecks = () => {
    setDecks(storage.getDecks())
  }


  const showToast = (message) => {
    setToast({ show: true, message })
    setTimeout(() => setToast({ show: false, message: '' }), 3000)
  }

  const handleDeleteCard = (cardId) => {
    if (window.confirm('确定要删除这张卡片吗？')) {
      storage.deleteCard(cardId)
      if (selectedDeck) {
        const updatedDeck = {
          ...selectedDeck,
          cardCount: selectedDeck.cardCount - 1,
          modified: new Date()
        }
        storage.saveDeck(updatedDeck)
        refreshDecks()
        setDeckCards(storage.getCardsByDeck(selectedDeck.id))
      }
    }
  }

  const handleCreateDeck = (name, description) => {
    const newDeck = {
      id: Date.now().toString(),
      name,
      description,
      cardCount: 0,
      created: new Date(),
      modified: new Date()
    }
    storage.saveDeck(newDeck)
    refreshDecks()
    return newDeck
  }

  const handleSaveCard = (cardData, editingCard, selectedDeck) => {
    const isEditing = editingCard !== null
    const newCard = {
      ...cardData,
      id: isEditing ? editingCard.id : Date.now().toString(),
      deck: selectedDeck.id,
      created: isEditing ? editingCard.created : new Date(),
      modified: new Date(),
      interval: isEditing ? editingCard.interval : 0,
      easeFactor: isEditing ? editingCard.easeFactor : 2.5,
      nextReview: isEditing ? editingCard.nextReview : new Date(),
      reviews: isEditing ? editingCard.reviews : 0,
      correct: isEditing ? editingCard.correct : 0,
      incorrect: isEditing ? editingCard.incorrect : 0
    }

    storage.saveCard(newCard)

    if (selectedDeck && !isEditing) {
      const updatedDeck = {
        ...selectedDeck,
        cardCount: selectedDeck.cardCount + 1,
        modified: new Date()
      }
      storage.saveDeck(updatedDeck)
      refreshDecks()
    }

    showToast(isEditing ? '卡片编辑成功' : '卡片添加成功')
    return newCard
  }

  const handleDeleteDeck = (deckId) => {
    if (window.confirm('确定要删除这个卡片组吗？删除后将无法恢复，该卡片组下的所有卡片也会被删除。')) {
      // 先删除该卡片组下的所有卡片
      const cards = storage.getCardsByDeck(deckId)
      cards.forEach(card => storage.deleteCard(card.id))
      
      // 删除卡片组
      storage.deleteDeck(deckId)
      refreshDecks()
      showToast('卡片组删除成功')
    }
  }

  return {
    decks,
    selectedDeck,
    deckCards,
    toast,
    setSelectedDeck,
    setDeckCards,
    refreshDecks,
    handleDeleteCard,
    handleCreateDeck,
    handleSaveCard,
    showToast,
    handleDeleteDeck
  }
}